<template>
	<view :style="[AppSkinVar]" class="e-rela">
		<scroll-view class="scroll-y" scroll-y @scrolltolower="getData" lower-threshold="60">
			<view class="">
				<view class="pay-success-header e-p-20 e-m-b-20 keep-all">
					<view class="text-center e-p-t-80 e-m-b-34">
						<template v-if="groupInfo">
							<view class="c-white e-font-36" v-if="groupInfo.groupNum === groupInfo.nowNum">
								{{$t('spellgroup.groupSuccess')}}
							</view>
							<view v-else class="c-white e-font-36">
								<text>{{$t('spellgroup.createSuccess')}}</text>
							</view>
						</template>
					</view>
					<view class="spell-panel e-p-b-40">
						<SepllPerson :type="2" :groupInfo="groupInfo"></SepllPerson>
						<view class="e-p-b-32 text-center e-font-24 c-333 e-flex-xy-center"
							v-if="groupInfo && !groupInfo.state">
							<text>{{$t('spellgroup.surplus')}}</text>
							<view class="e-flex c-red e-font-28 e-m-l-12 e-m-r-12">
								<view class="red-box">
									{{hours}}
								</view>
								:
								<view class="red-box">
									{{minute}}
								</view>
								:
								<view class="red-box">
									{{seconds}}
								</view>
							</view>
							<text v-if="!$isEnglishVersion">{{$t('spellgroup.end')}}</text>
						</view>
						<view v-if="groupInfo" class="spell-btn e-flex-xy-center e-m-l-40 e-m-r-40" @tap="getQRCodeUrl">
							<text v-if="!groupInfo.state" class="e-font-30 c-white">{{$t('spellgroup.yqhypt')}}</text>
							<text v-else class="e-font-30 c-white">{{$t('spellgroup.fhsy')}}</text>
						</view>
						<view v-else class="spell-btn e-flex-xy-center e-m-l-40 e-m-r-40" @tap="handleGetGoodsInfo">
							<text class="e-font-30 c-white">{{$t('spellgroup.reload')}}</text>
						</view>
					</view>
				</view>
				<view class="e-p-20 bg-white spell-strategy keep-all text-center">
					<view class="c-333 e-font-28 e-m-b-20">
						<text class="fw-600">{{$t('spellgroup.ptgl')}}</text>
					</view>
					<view class="e-flex e-p-b-20">
						<view class="e-flex-1 e-flex e-flex-column e-flex-center">
							<image class="img-56" src="../static/spell-bag.png" mode=""></image>
							<view class="">
								{{$t('spellgroup.kthct')}}
							</view>
							<view class="" v-if="!$isEnglishVersion">
								{{$t('spellgroup.xtgj')}}
							</view>
						</view>
						<view class="">
							<image class="img-24-12" src="../static/spell-arrow.png" mode=""></image>
						</view>
						<view class="e-flex-1 e-flex e-flex-column e-flex-center">
							<image class="img-56" src="../static/spell-add.png" mode=""></image>
							<view class="">
								{{$t('spellgroup.yqhy')}}
							</view>
							<view class="" v-if="!$isEnglishVersion">
								{{$t('spellgroup.ctyhd')}}
							</view>
						</view>
						<view class="">
							<image class="img-24-12" src="../static/spell-arrow.png" mode=""></image>
						</view>
						<view class="e-flex-1 e-flex e-flex-column e-flex-center">
							<image class="img-56" src="../static/spell-delivery.png" mode=""></image>
							<view class="">
								{{$t('spellgroup.rmkt')}}
							</view>
							<view class="" v-if="!$isEnglishVersion">
								{{$t('spellgroup.bmtk')}}
							</view>
						</view>
					</view>
				</view>
				<view class="h-100" v-if="goodsList.length">
					<text class="fw-600 c-333 e-font-28">{{$t('spellgroup.zlyd')}}</text>
				</view>
				<view class="e-flex e-flex-wrap e-p-l-20 e-p-r-20" v-if="goodsList.length">
					<goods-item style="width:calc(50% - 12rpx);" :style="{'margin-right': (index+1)%2===1 ?'20rpx':''}"
						v-for="(item,index) in goodsList" :key="item.id" :item="item"></goods-item>
				</view>
				<view class="e-flex e-flex-xy-center" v-if="goodsList.length">
					<load-more :showLoad="showLoad"></load-more>
				</view>
			</view>
		</scroll-view>
		<!-- #ifndef MP-WEIXIN ||MP-ALIPAY-->
		<share-popup type="1" :mpShareUrl="mpShareUrl" :show="sharePopupShow"
			@close="sharePopupShow = false"></share-popup>
		<!-- #endif -->
		<view class="canvas-box  e-abso">
			<canvas ref="canvas" class="goodsInfo-canvas " id="goodsInfo-canvas" canvas-id="goodsInfo-canvas"></canvas>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import SepllPerson from '../child/spellPerson.vue'
	import GoodsItem from './child/goodsItem.vue'
	// #ifdef PRIVATE || SUBSCRIPTION
	import {
		getShareLink
	} from '@/common/wxInit'
	// #endif
	// #ifdef MP
	import { sceneParamsToObj } from '@/common/utils'
	// #endif
	import { getActivityGroupList, getGroupByPayCode, getGoodsShareUrl } from '@/common/request/api'
	import type { GroupByPayData } from '@/common/request/api'
	import type { RequestFromType } from '@/common/request/type'
	/* 引入uqrcode核心js */
	import { getInterval, padZero, uQRCode, getAppImageInfo } from '@/common/utils'
	import { drawQRCode, drawRoundedRectangle, drawText, getTextLineHeight } from '@/common/canvas'
	import { useCurrentInstance, useQueryPage, useCanvas } from '@/common/hooks'
	import type { RecordAny } from '@/typings/utils'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import { useGlobal } from '@/common/stores'
	import {
		storeToRefs
	} from 'pinia'


	const ctx = useCurrentInstance()
	const { canvasdraw, canvasImgUrl: mpShareUrl } = useCanvas()

	const {
		global
	} = storeToRefs(useGlobal())

	let timer : number | undefined = undefined

	const hours = ref('')
	const minute = ref('')
	const seconds = ref('')

	const {
		showLoad,
		isEmpty,
		list: goodsList,
		handleQueryPage,
		handleRefresh
	} = useQueryPage({
		api: getActivityGroupList
	})

	const groupInfo = ref<GroupByPayData | null>(null)
	const sharePopupShow = ref(false)

	let pageParams : RecordAny = { paycode: '' }


	const handleGetGoodsInfo = () => {
		pageParams.paycode && getGroupByPayCode({ payCode: pageParams.paycode }).then(async res => {
			groupInfo.value = res.data
			// state 0拼团中 1拼团成功 2拼团失败退款
			if (groupInfo.value) {
				startCountdown(res.data.overTime)
				// 页面分享的初始化
				let goodsInfo = res.data.deputy[0]
				shareInit(goodsInfo)
				if (res.data.state === 1) {
					groupInfo.value.nowNum = res.data.groupNum
					groupInfo.value.headUrls.length = res.data.groupNum
				} else if (res.data.state === 2) {
					uni.navigateTo({
						url: '/'
					})
				}
			} else {
				setTimeout(() => {
					handleGetGoodsInfo()
				}, 1000)
			}

		})
	}
	const getData = () => {
		handleQueryPage()
	}
	// 拼团倒计时
	const startCountdown = (time : string) => {

		const overTime = new Date(time).getTime()
		const nowTime = new Date().getTime()
		if (overTime > nowTime) {
			const date = getInterval(overTime)
			hours.value = padZero(date.h)
			minute.value = padZero(date.m)
			seconds.value = padZero(date.s)
			timer = setTimeout(() => { startCountdown(time) }, 1000)
		} else {
			clearTimeout(timer)
			timer = undefined
			if (!groupInfo.value?.state) {
				handleGetGoodsInfo()
			}

		}
	}
	// 如果是小程序，获取的是分享卡片上的二维码地址
	// h5获取的是分享的当前页面地址
	const getQRCodeUrl = () => {
		if (groupInfo.value?.state) {
			uni.navigateTo({
				url: '/'
			})
			return
		}
		let url
		let formType : RequestFromType
		// #ifdef MP-WEIXIN||MP-ALIPAY
		url = '/pages/spellGroup/invitation/index'
		// #endif
		// #ifndef MP-WEIXIN||MP-ALIPAY
		url = '/pages/spellGroup/invitation/index'
		// #endif
		// #ifdef  PRIVATE
		formType = 'mp_private'
		// #endif
		// #ifndef  PRIVATE
		formType = getApp().globalData?.payFromType
		// #endif
		getGoodsShareUrl({
			url,
			formType,
			scene: ctx.$getShareUrlScene(`paycode=${pageParams.paycode}&groupCode=${groupInfo.value!.groupCode}`)
		}).then(res => {
			draw(res.shareUrl)
		})
	}
	const draw = async (shareUrl : string) => {
		canvasdraw({
			bgImgUrl: ctx.$fullLink(groupInfo.value!.deputy[0].commodityUrl),
			canvasId: 'goodsInfo-canvas',
			that: ctx,
			width: 290,
			height: 290,
			bgWidth: 290,
			bgHeight: 290,
			async drawIng(canvasCtx) {
				let { name = '', price } = { name: groupInfo.value!.deputy[0].commodityName, price: groupInfo.value!.deputy[0].deputyMoney }
				const $unitEn = global.value.unitEn
				drawText(canvasCtx, {
					x: 20,
					y: 320,
					text: $unitEn,
					size: 10,
					fillStyle: '#F5222D',
					font: 'normal normal bold 10px'
				})
				drawText(canvasCtx, {
					x: 22 + canvasCtx.measureText($unitEn).width,
					y: 320,
					text: price,
					size: 22,
					fillStyle: '#F5222D',
					font: 'normal normal bold 22px'
				})
				canvasCtx.setFontSize(14);
				let { row: textList } = getTextLineHeight(canvasCtx, {
					w: 100,
					text: name
				})
				drawText(canvasCtx, {
					x: 20,
					y: 348,
					text: textList[0],
					size: 14,
					fillStyle: '#333',
					font: 'normal normal bold 14px'
				})
				if (textList.length > 2) {
					textList[1] = textList[1].substr(0, textList[1].length - 2) + '...'
				}
				textList[1] &&
					drawText(canvasCtx, {
						x: 20,
						y: 368,
						text: textList[1],
						size: 14,
						fillStyle: '#333',
						font: 'normal normal bold 14px'
					})
				// #ifdef MP-WEIXIN||MP-ALIPAY
				let codePath = await getAppImageInfo(ctx.$fullLink(shareUrl))
				if (codePath.path) {
					canvasCtx.drawImage(codePath.path, 208, 310, 65, 65)
				}
				// #endif
				// #ifndef MP-WEIXIN||MP-ALIPAY
				drawRoundedRectangle(canvasCtx, {
					x: 208,
					y: 310,
					width: 65,
					height: 65,
					radius: 0,
					lineWidth: 2,
					strokeStyle: '#E7E7E7'
				})
				drawQRCode(canvasCtx, {
					x: 213,
					y: 315,
					size: 55, //二维码大小
					margin: 0, // 填充边距
					modules: uQRCode.getModules({
						id: 'goodsInfo-canvas', //canvasId
						mode: 'canvas', // 生成模式
						size: 55, //二维码大小
						margin: 0, // 填充边距
						backgroundColor: '#fff', // 背景色
						foregroundColor: '#000', // 前景色
						errorCorrectLevel: uQRCode.errorCorrectLevel.H, // 纠错等级,
						text: shareUrl
					})
				})
				// #endif
			}
		}).then(() => {
			showShare()
		})
	}
	const showShare = () => {
		// #ifdef MP-WEIXIN
		wx.showShareImageMenu({
			path: mpShareUrl.value
		})
		// #endif
		// #ifndef MP-WEIXIN
		sharePopupShow.value = true
		// #endif
	}
	const shareInit = (goodsInfo : GroupByPayData['deputy'][0]) => {
		let imgUrls = goodsInfo?.commodityUrl ? goodsInfo.commodityUrl : ''
		// #ifdef APP-PLUS
		uni.$endless.mpShare = {
			title: goodsInfo.name,
			path: '',
			appDesc: goodsInfo.shareMsg || '',
			imageUrl: ctx.$fullLink(imgUrls),
			appParams: pageParams
		}
		// #endif

		// #ifdef MP-WEIXIN||MP-ALIPAY
		uni.$endless.mpShare = {
			title: goodsInfo.name,
			path: '', // 默认为当前页面路径
			imageUrl: ctx.$fullLink(imgUrls)
		}
		// #endif
		// #ifdef PRIVATE || SUBSCRIPTION
		uni.$endless.mpShare = {
			title: goodsInfo.name,
			link: getShareLink(),
			desc: goodsInfo.shareMsg || '',
			imgUrl: ctx.$fullLink(imgUrls)
		}
		ctx.mpShareInit()
		// #endif
	}


	onLoad((opt) => {
		let query = opt
		// #ifdef MP-WEIXIN
		if (opt?.scene) {
			query = sceneParamsToObj(opt.scene)
		}
		// #endif

		pageParams = query

		handleGetGoodsInfo()
		handleRefresh()
	})
</script>

<style lang="scss" scoped>
	.scroll-y {
		height: 100vh;
	}

	.pay-success-header {
		background: linear-gradient(360deg, #F5222D 0%, #FF6B65 100%);
		height: 412rpx;
		position: relative;
	}

	.spell-panel {
		background: #FFFFFF;
		border-radius: 10rpx;
	}

	.spell-btn {
		height: 90rpx;
		background: #F5222D;
		border-radius: 45rpx;
	}

	.red-box {
		background: rgba(245, 34, 45, 0.1);
		border-radius: 4px;
		padding: 2rpx;
		line-height: 32rpx;
		margin: 0 6rpx;
	}

	.spell-strategy {
		margin: 0 20rpx;
		padding: 20rpx;
		background: #FFFFFF;
		border-radius: 10rpx;
		margin-top: 250rpx;
	}

	.img-24-12 {
		width: 24rpx;
		height: 12rpx;
	}

	.e-flex-column {
		flex-direction: column;
	}

	.h-100 {
		height: 100rpx;
		line-height: 100rpx;
		padding-left: 20rpx;
	}

	.canvas-box {
		left: -9999px;
		top: -9999px;

		.goodsInfo-canvas {
			width: 290px;
			height: 390px;
			font-kerning: normal;
		}
	}
</style>